<?php

namespace app\data\controller\user;
use app\data\model\DataDistributionQueue;
use app\data\model\DataUserDistribution;
use app\data\model\DataUser;
use app\data\service\UserAdminService;
use think\admin\Controller;

/**
 * 分销审核管理
 */
class Distribution  extends Controller
{
    /**
     * 分销申请列表
     * @auth true
     * @return void
     */
    public function index()
    {
        $this->title = '分销申请管理';
        // 订单列表查询
        $query = DataUserDistribution::mQuery();
        $query->equal('status')->dateBetween('apply_time,audit_time');
        // 搜索查询
        $db = DataUser::mQuery()->like('phone|username|nickname#name')->db();
        if ($db->getOptions('where')) $query->whereRaw("uuid in {$db->field('id')->buildSql()}");
         // 分页排序处理
        $lists = $query->order('apply_time desc')->page();
    }
    /**
     * 列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _index_page_filter(array &$data)
    {
        UserAdminService::buildByUid($data);
    }
    /**
     * 分销审批
     * @auth true
     * @return void
     */
    public function audit(){
        $id = input('id','','trim,intval');
        if(empty($id)){
            return \Tools::returnMsg(false,array(
                'code'  => '10015',
                'message'=>'参数错误'
            ));
        }
        if($this->request->isPost()){
            $status = input('status',1);//1通过  2  驳回
            $audit_remark = input('audit_remark','');//备注
            $first_rate = input('first_rate',10,'trim,intval');//一级分佣比例
            $secont_rate = input('secont_rate',1,'trim,intval');//二级分佣比例
            if($first_rate > 100 || $first_rate < 0){
                return \Tools::returnMsg(false,array(
                    'code'  => '10015',
                    'message'=>'参数错误'
                ));
            }
            if($secont_rate > 100 || $secont_rate < 0){
                return \Tools::returnMsg(false,array(
                    'code'  => '10015',
                    'message'=>'参数错误'
                ));
            }
            $handlename = session('user.username');
            //更新记录状态
            //更新用户状态
            if($status == 1){
                $remark = $handlename.'通过';
            }else{
                $remark = $handlename.'驳回';
            }
            $opera = [];
            DataUserDistribution::mk()->startTrans();
            $applyinfo = DataUserDistribution::mk()->where(['id'=>$id])->find()->toArray();
            $userinfo = DataUser::mk()->where(array('id'=>$applyinfo['uuid']))->field('username')->find()->toArray();
            if(empty($userinfo)) $userinfo['username'] = '';
            $opera[] = DataUserDistribution::mk()->update([
                'status' => $status,
                'audit_remark'=>$remark.$userinfo['username'].'的分销申请，备注：'.$audit_remark,
                'audit_time'=>\Tools::getDateTimeByTime(),
                'first_rate'    =>$first_rate,
                'secont_rate'   =>$secont_rate
            ],array(
                'id'    => $id
            ));
            if($status == 1) {
                //更新用户分销员身份
                $opera[] = DataUser::mk()->where(['id' => $applyinfo['uuid']])->save(array(
                    'is_distribution' => 1,
                    'dis_path'=>"#*#".$applyinfo['uuid']."#*#",
                    'distribution_time' => \Tools::getDateTimeByTime(),
                    'distribution_code' => \Common::uniqidDate(16, 'D' . $applyinfo['uuid'])
                ));
                //添加分销员队列
                $opera[] = DataDistributionQueue::mk()->create(array(
                    'user_id'       => $applyinfo['uuid'],
                    'pre_id'        => $userinfo['pre_dis_id']??0,
                    'pre_pre_id'    => $userinfo['pre_pre_dis_id']??0,
                    'create_time'   => \Tools::getDateTimeByTime()
                ));
            }
            //判断是否有账号
            $accountModel = new \app\api\model\DataUserAccount();
                $accountInfo = $accountModel->getOne(array(
                    'uuid'  => $applyinfo['uuid']
                ),'id');
                if(empty($accountInfo)){
                    $data['create_at']  = \Tools::getDateTimeByTime();
                    $data['uuid']   = $applyinfo['uuid'];
                    $opera[] = $accountModel->addData($data);
                }
            sysoplog('审核分销员申请',$remark.$userinfo['username']);
            if(\Tools::checkArrayResult($opera)){
                DataUserDistribution::mk()->commit();
                return \Tools::returnMsg(true,$opera);
            }else{
                DataUserDistribution::mk()->rollBack();
                return \Tools::returnMsg(false,array(
                    'code'  => '10017',
                    'message'=>'审核失败'
                ));
            }
        }else{
            $this->id = $id;
        }
        $this->fetch();
    }
    /**
     * 编辑
     * @auth true
     * @return void
     */
    public function edit(){
        $id = input('id','','trim,intval');
        if(empty($id)){
            return \Tools::returnMsg(false,array(
                'code'  => '10015',
                'message'=>'参数错误'
            ));
        }
        if($this->request->isPost()){
            $first_rate = input('first_rate',10,'trim,intval');//一级分佣比例
            $secont_rate = input('secont_rate',1,'trim,intval');//二级分佣比例
            if($first_rate > 100 || $first_rate < 0){
                return \Tools::returnMsg(false,array(
                    'code'  => '10015',
                    'message'=>'参数错误'
                ));
            }
            if($secont_rate > 100 || $secont_rate < 0){
                return \Tools::returnMsg(false,array(
                    'code'  => '10015',
                    'message'=>'参数错误'
                ));
            }
            $handlename = session('user.username');
            $applyinfo = DataUserDistribution::mk()->where(['id'=>$id])->find()->toArray();
            $userinfo = DataUser::mk()->where(array('id'=>$applyinfo['uuid']))->field('username')->find()->toArray();
            if(empty($userinfo)) $userinfo['username'] = '';
            $opera[] = DataUserDistribution::mk()->update([
                'first_rate'    =>$first_rate,
                'secont_rate'   =>$secont_rate
            ],array(
                'id'    => $id
            ));
            sysoplog('更改分佣比例',$handlename.'更改分佣比例'.$userinfo['username']);
            if(\Tools::checkArrayResult($opera)){
                return \Tools::returnMsg(true,$opera);
            }else{
                return \Tools::returnMsg(false,array(
                    'code'  => '10017',
                    'message'=>'更改失败'
                ));
            }
        }else{
            $this->id = $id;
        }
        $this->fetch();
    }
}
